package org.jeecg.modules.demo.dept.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.dept.service.IDeptService;
import org.jeecg.modules.demo.dto.DeptDto;
import org.jeecg.modules.demo.entity.Dept;
import org.jeecg.modules.demo.mall.api.MallHelloApi;
import org.jeecg.modules.demo.mall.entity.YxUser;
import org.jeecg.modules.demo.util.Allinpay;
import org.jeecg.modules.demo.weixin.api.WeixinHelloApi;
import org.jeecg.modules.demo.weixin.entity.MerchantPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: dept
 * @Author: jeecg-boot
 * @Date: 2023-10-19
 * @Version: V1.0
 */
@Api(tags = "商户表")
@RestController
@RequestMapping("/upms/dept/dept")
@Slf4j
public class DeptController extends JeecgController<Dept, IDeptService> {
    @Autowired
    private IDeptService deptService;
    @Resource
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private MallHelloApi mallHelloApi;
    @Autowired
    private WeixinHelloApi weixinHelloApi;

    /**
     * 分页列表查询
     *
     * @param dept
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "dept-分页列表查询")
    @ApiOperation(value = "dept-分页列表查询", notes = "dept-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<Dept>> queryPageList(Dept dept,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             @RequestParam(name = "deptIds", defaultValue = "") String deptIds,
                                             HttpServletRequest req) {
        QueryWrapper<Dept> queryWrapper = QueryGenerator.initQueryWrapper(dept, req.getParameterMap());
        if (dept.getId() != null) {
            queryWrapper.eq("id", dept.getId());
        }
        if (StringUtils.hasText(dept.getAgentMerchant())) {
            String[] split = dept.getAgentMerchant().split(",");
            List<Long> longs = Arrays.stream(split).map(a -> Long.valueOf(a)).collect(Collectors.toList());
            queryWrapper.in("agent_merchant", longs);
        }
        queryWrapper.eq("pid", 15);
        queryWrapper.orderByDesc("create_time");
        if (StringUtils.hasText(deptIds)) {
            List<Long> deptIdList = Arrays.asList(deptIds.split(",")).stream().map(s -> {
                return Long.parseLong(s);
            }).collect(Collectors.toList());
            queryWrapper.in("id", deptIdList);
        }
        Page<Dept> page = new Page<Dept>(pageNo, pageSize);
        IPage<Dept> pageList = deptService.page(page, queryWrapper);
        if (pageList == null) {
            return Result.ok();
        }
        pageList.getRecords().forEach(dept1 -> {
            MerchantPay merchantPay = weixinHelloApi.querySpecial(String.valueOf(dept1.getId()));
            if (merchantPay != null) {
                dept1.setSpecialSubMerchants(merchantPay.getSpecialSubMerchants());
            }
        });
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param dept
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "dept-分页列表查询")
    @ApiOperation(value = "dept-分页列表查询", notes = "dept-分页列表查询")
    @PostMapping(value = "/postList")
    public Result<IPage<Dept>> postList(Dept dept,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                        @RequestParam(name = "deptIds", defaultValue = "") String deptIds,
                                        HttpServletRequest req) {
        QueryWrapper<Dept> queryWrapper = QueryGenerator.initQueryWrapper(dept, req.getParameterMap());
        queryWrapper.eq("pid", 15);
        queryWrapper.orderByDesc("create_time");
        if (StringUtils.hasText(deptIds)) {
            List<Long> deptIdList = Arrays.asList(deptIds.split(",")).stream().map(s -> {
                return Long.parseLong(s);
            }).collect(Collectors.toList());
            queryWrapper.in("id", deptIdList);
        }
        Page<Dept> page = new Page<Dept>(pageNo, pageSize);
        IPage<Dept> pageList = deptService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 不分页列表查询
     *
     * @return
     */
    //@AutoLog(value = "dept-分页列表查询")
    @ApiOperation(value = "dept-不分页列表查询", notes = "dept-不分页列表查询")
    @GetMapping(value = "/queryList")
    public Result<?> queryNoPageList(@RequestParam Long id, Integer merchantType) {
        if (id != null) {
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pid", 15);
            queryWrapper.eq("id", id);
            if (merchantType != null) {
                queryWrapper.eq("merchant_type", merchantType);
            }
            Dept dept = deptService.getOne(queryWrapper);
            return Result.OK(dept);
        }
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", 15);
        if (merchantType != null) {
            queryWrapper.eq("merchant_type", merchantType);
        }
        List<Dept> deptList = deptService.list(queryWrapper);
        return Result.OK(deptList);
    }

    /**
     * 添加
     *
     * @param dept
     * @return
     */
    @AutoLog(value = "dept-添加")
    @ApiOperation(value = "dept-添加", notes = "dept-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Dept dept) {
        dept.setId(Long.parseLong(RandomUtil.randomNumbers(3)));
        deptService.save(dept);
        MerchantPay merchantPay = new MerchantPay();
        merchantPay.setMerchantId(Integer.valueOf(String.valueOf(dept.getId())));
        merchantPay.setSpecialSubMerchants(dept.getSpecialSubMerchants());
        dept.setBizUserId("SH" + RandomUtil.randomNumbers(6));
//        JSONObject member = Allinpay.createMember(dept.getBizUserId(), 2L);
//        if (member==null){
//            return Result.error("会员创建失败");
//        }
        weixinHelloApi.add(merchantPay);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param dept
     * @return
     */
    @AutoLog(value = "dept-编辑")
    @ApiOperation(value = "dept-编辑", notes = "dept-编辑")
    @PutMapping(value = "/edit")
    public Result<String> edit(@RequestBody Dept dept) {
        deptService.updateById(dept);
        if (StringUtils.hasText(dept.getSpecialSubMerchants())) {
            MerchantPay merchantPay = new MerchantPay();
            merchantPay.setMerchantId(Integer.valueOf(String.valueOf(dept.getId())));
            merchantPay.setSpecialSubMerchants(dept.getSpecialSubMerchants());
            weixinHelloApi.updateSpecial(merchantPay);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 商家生成代理商
     *
     * @param dept
     * @return
     */
    @AutoLog(value = "商家升级为代理商")
    @ApiOperation(value = "商家升级为代理商", notes = "商家升级为代理商")
    @PutMapping(value = "/updateMer")
    public Result<String> updateMer(@RequestBody Dept dept) {
        if (dept.getId() == null) {
            return Result.error("没有传对应门店的id");
        }
        //先查询是否填写了商家信息
        MerchantPay merchantPay1 = weixinHelloApi.querySpecial(String.valueOf(dept.getId()));
        if (merchantPay1 == null) {
            return Result.error("请先填写商家管理信息！");
        }
        //修改商家的类型    商家升级代理商过着商家
        UpdateWrapper<Dept> deptUpdateWrapper = new UpdateWrapper<>();
        deptUpdateWrapper.set("merchant_type", dept.getMerchantType());
        deptUpdateWrapper.set("merchant_balance", dept.getAgentMerchant());
        deptUpdateWrapper.eq("id", dept.getId());
        deptService.updateById(dept);

        if (StringUtils.hasText(dept.getAgentMerchant())) {
            List<Dept> depts = deptService.listByIds(Arrays.asList(dept.getAgentMerchant().split(",")));
            depts.forEach(dept1 -> dept1.setAgentMerchant(dept.getId().toString()));
            deptService.updateBatchById(depts);
        }

//        depts.forEach(dept1 -> );
        //修改对应信
//        MerchantPay merchantPay = new MerchantPay();
//        merchantPay.setMerchantId(Integer.valueOf(String.valueOf(dept.getId())));
//        merchantPay.setSpecialSubMerchants(dept.getSpecialSubMerchants());
//        weixinHelloApi.updateSpecial(merchantPay);
        return Result.OK("已升级为代理商!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "dept-通过id删除")
    @ApiOperation(value = "dept-通过id删除", notes = "dept-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        deptService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "dept-批量删除")
    @ApiOperation(value = "dept-批量删除", notes = "dept-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.deptService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "dept-通过id查询")
    @ApiOperation(value = "dept-通过id查询", notes = "dept-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Dept> queryById(@RequestParam(name = "id", required = true) String id) {
        Dept dept = deptService.getById(id);
        if (dept == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dept);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "店铺id查询", notes = "店铺id查询")
    @GetMapping(value = "/queryByDeptId")
    public Dept queryByDept(@RequestParam(name = "id", required = true) Long id) {
        Dept dept = deptService.getById(String.valueOf(id));
        if (dept == null) {
            return null;
        }
        return dept;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param dept
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Dept dept) {
        return super.exportXls(request, dept, Dept.class, "dept");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Dept.class);
    }

    /**
     * 根据用户名查询商户的id
     *
     * @return
     */
    @GetMapping(value = "/queryMerchantId")
    public Result<?> queryMerchantId(@RequestParam("username") String username) {
        Map<String, Object> resultMap = new HashMap<>();
        //查询当前登录用户是否是平台管理员
        LoginUser userByName = sysBaseAPI.getUserByName(username);
        String roleId = sysBaseAPI.getRolesUserById(userByName.getId());
        if (org.apache.commons.lang3.StringUtils.isBlank(roleId)) {
            return Result.error(606, "当前用户暂未分配权限，请联系平台管理员分配!");
        }
        if (roleId.equals("f6817f48af4fb3af11b9e8bf182f618b") || roleId.equals("1716993885818384385")) {
            resultMap.put("status", 1);
            return Result.OK(resultMap);
        }
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_ids", username);
        List<Dept> list = deptService.list(queryWrapper);
        if (list.size() == 0) {
            return Result.error(606, "当前用户暂无绑定商家！");
        }
        resultMap.put("status", 2);
        resultMap.put("data", list);
        return Result.OK(resultMap);
    }


    /**
     * 根据用户名查询商户的id
     *
     * @return
     */
    @GetMapping(value = "/queryMerchantUser")
    public Result<?> queryMerchantUser(@RequestParam("username") String username) {
        Map<String, Object> resultMap = new HashMap<>();
        //查询当前登录用户是否是平台管理员
        LoginUser userByName = sysBaseAPI.getUserByName(username);
        String roleId = sysBaseAPI.getRolesUserById(userByName.getId());
//        if (org.apache.commons.lang3.StringUtils.isBlank(roleId)) {
//            return Result.error(606, "当前用户暂未分配权限，请联系平台管理员分配!");
//        }
        if (roleId != null && roleId.equals("1716420501254438913")) {
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("user_ids", username);
            List<Dept> list = deptService.list(queryWrapper);
            if (list.size() == 0) {
                return Result.error(606, "当前用户暂无绑定商家！");
            }
            resultMap.put("status", 1);
            resultMap.put("data", list);
            return Result.OK(resultMap);
        }
        if (userByName.getMerchantId() == null) {
            return Result.error(606, "当前用户暂无绑定商家！");
        }
        resultMap.put("status", 2);
        resultMap.put("data", userByName);
        return Result.OK(resultMap);
    }

    @GetMapping(value = "/querySysUser")
    public Result<?> queryMerchantId(@RequestParam("deptId") Long deptId) {
        Dept byId = deptService.getById(deptId);
        String userIds = byId.getUserIds();
        List<LoginUser> loginUsers = sysBaseAPI.queryNames(userIds);
        return Result.OK(loginUsers);
    }

    /**
     * 新增商品时查询商家
     */
    @PostMapping(value = "/queryMerchant")
    public Result<?> queryMerchant(@RequestBody DeptDto deptDto) {
        List<Dept> deptList = new ArrayList<>();
        Arrays.stream(deptDto.getDeptIds()).forEach(dto -> {
            Dept byId = deptService.getById(dto);
            deptList.add(byId);
        });
        return Result.OK(deptList);
    }

    /**
     * 新增商品时查询商家
     */
    @GetMapping(value = "/updateDeptPric")
    public void updateDeptPric(@RequestParam Long merId, @RequestParam BigDecimal price) {
        Dept dept = deptService.getById(merId);
        if (dept != null) {
            dept.setMerchantBalance(dept.getMerchantBalance().subtract(price));
        }
    }

    @GetMapping(value = "/updateUserIds")
    public void updateUserIds(@RequestParam String username, @RequestParam String merId) {
        Dept byId = deptService.getById(merId);
        if (byId != null) {
            byId.setUserIds(byId.getUserIds() + "," + username);
            deptService.updateById(byId);
        }
    }

    /**
     * 商家绑定小程序进来的商家管理员
     */
    @PostMapping(value = "/bindAppUser")
    public Result<?> bindAppUser(@RequestBody DeptDto deptDto) {
        YxUser user = new YxUser();
        user.setMerchantId(Integer.valueOf(deptDto.getMerId()));
        Arrays.stream(deptDto.getUid().split(",")).forEach(s -> {
            user.setUid(Integer.valueOf(s));
            mallHelloApi.updateMerchant(user);
        });
        return Result.OK();
    }

    @GetMapping(value = "/sendVerificationCode")
    public Result<?> sendVerificationCode(@RequestBody DeptDto deptDto) {
        JSONObject jsonObject = Allinpay.sendVerificationCode(deptDto.getBizUser(), deptDto.getPhone());
        if (jsonObject == null) {
            return Result.error("发送验证失败！");
        }
        return Result.OK();
    }


    @GetMapping(value = "/bindPhone")
    public Result<?> bindPhone(@RequestBody DeptDto deptDto) {
        JSONObject jsonObject = Allinpay.bindPhone(deptDto.getBizUser(), deptDto.getPhone(), deptDto.getCode());
        if (jsonObject == null) {
            return Result.error("绑定手机号码失败");
        }
        UpdateWrapper<Dept> deptUpdateWrapper = new UpdateWrapper<>();
        deptUpdateWrapper.eq("id", String.valueOf(deptDto.getMerId()));
        deptUpdateWrapper.set("bind_phone_number", deptDto.getPhone());
        deptService.update(deptUpdateWrapper);
        return Result.OK();
    }


    /**
     * 分页列表查询
     *
     * @param dept
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "dept-分页列表查询")
    @ApiOperation(value = "代理商查看门店", notes = "代理商查看门店")
    @GetMapping(value = "/queryDls")
    public Result<IPage<Dept>> queryDls(Dept dept,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                        @RequestParam(name = "deptIds", defaultValue = "") String deptIds,
                                        HttpServletRequest req) {
        QueryWrapper<Dept> queryWrapper = QueryGenerator.initQueryWrapper(dept, req.getParameterMap());
        queryWrapper.eq("pid", 15);
        queryWrapper.isNull("agent_merchant");
        queryWrapper.ne("id", dept.getId());
        queryWrapper.orderByDesc("create_time");
        Page<Dept> page = new Page<Dept>(pageNo, pageSize);
        IPage<Dept> pageList = deptService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


}
